<template>
  <div>
    <a
      href="#"
      role="button"
      class="text-white"
      :class="{ 'btn-disabled': isLoading }"
      :aria-disabled="isLoading"
      :disabled="isLoading"
      @click="download()"
    >
      <span
        v-if="isLoading"
        class="spinner-border spinner-border-sm"
        role="status"
      />
      <span v-else>
        {{ $t(buttonLabel) }}
      </span>
    </a>

    <!-- Used for the design -->
    <!-- Page -->
    <div ref="modelPrintSection" id="modelPrintSection" style="
        display: none;
        position: relative;
        color: #000;
        min-width: 90em;
        padding: 1rem;
        background: #ffffff;
        text-transform: initial;
    ">
        <!-- Img section -->
        <div class="d-flex flex-column text-left" style="
          border: 2px solid #56A1E4;
          border-radius: 8px;
          background: #ffffff;
          padding: 1rem;
        ">
          <div class="d-flex justify-content-center align-items-center" style="min-height: 45em;padding: 3em 0 3em 0;">
            <img :src="modelImg" :alt="title">
          </div>
          <div><h5><img src="/img/icon-pmlogo.png" alt="ProcessMaker logo" style="height: 30px;" class="mr-1"><b>Powered By ProcessMaker AI</b></h5></div>
          <div class="d-flex justify-items-between">
            <div class="w-50 text-muted"><small>Process Model Autogenerated by ProcessMaker AI {{ requestDate }}</small></div>
            <div class="w-50 text-muted text-right"><small>Generate your own process map at <span class="text-primary">https://processmaker.com/ai</span></small></div>
          </div>
        </div>

        <!-- Footer -->
        <div class="mt-3 text-left d-flex" style="
            border: 2px solid #56A1E4;
            border-radius: 8px;
            background: #ffffff;
        ">
          <div class="w-50 p-3" style="background: #E5F1FF; border-radius: 8px 0 0 8px"><h5><b>{{ title }}</b></h5></div>
          <div class="w-50 p-3 text-muted" style="border-radius: 0 8px 8px 0"><small>{{ prompt }}</small></div>
        </div>
      </div>
    </div>
</template>

<script>
export default {
  props: {
    svg: {
      type: String,
      required: true,
    },
    fileName: {
      type: String,
      default: "document",
    },
    title: {
      type: String,
      default: "",
    },
    description: {
      type: String,
      default: "",
    },
    prompt: {
      type: String,
      default: "",
    },
    requestDate: {
      type: String,
      default: "",
    },
    buttonLabel: {
      type: String,
      default: "Download",
    },
    watermarkText: {
      type: String,
      default: "Powered by ProcessMaker",
    },
  },
  data() {
    return {
      isLoading: false,
      modelImg: null,
      img: null,
    };
  },
  async mounted() {
    const svgString = await this.convertImagesToBase64(this.svg);
    this.modelImg = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;
  },
  methods: {
    async download(event) {
      this.isLoading = true;
      const el = this.$refs.modelPrintSection;

      this.$html2canvas(el, {
        logging: false,
        type: "dataURL",
        onclone(clone) {
          clone.getElementById("modelPrintSection").style.display = "block";
        },
      }).then((canvas) => {
        this.img = canvas;
        const dataURL = this.img;

        const downloadLink = document.createElement("a");
        downloadLink.href = dataURL;
        downloadLink.download = `${this.fileName}.png`;

        document.body.appendChild(downloadLink);
        downloadLink.click();

        document.body.removeChild(downloadLink);
        this.isLoading = false;
      });
    },

    async convertImagesToBase64(svgString) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(svgString, "image/svg+xml");
      const images = doc.querySelectorAll("image");

      // Convert URL image to base64.
      async function fetchImageAsBase64(url) {
        const response = await fetch(url);
        const blob = await response.blob();
        return new Promise((resolve) => {
          const reader = new FileReader();
          reader.onload = () => resolve(reader.result);
          reader.readAsDataURL(blob);
        });
      }

      // eslint-disable-next-line no-restricted-syntax
      for (const img of images) {
        const href = img.getAttributeNS("http://www.w3.org/1999/xlink", "href");
        if (href && href.startsWith("http")) {
          // eslint-disable-next-line no-await-in-loop
          const base64Data = await fetchImageAsBase64(href);
          img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", base64Data);
        }
      }

      return new XMLSerializer().serializeToString(doc);
    },
  },
};
</script>
